<?php 

class AskController extends CommonController{
	public function index(){
		if(!isset($_SESSION['uname']) || !isset($_SESSION['uid'])){
			$this->error('请登录后提问');
		}
		if(IS_POST){
			if(!$_POST['content'])$this->error("提问内容不能为空");
			if(!$_POST['cid'])$this->error("请选择提问类型");
			if(isset($_SESSION['uname']) && isset($_SESSION['uid'])){
				$data = array(
				'content' => $_POST['content'],
				'time'    => time(),
				'reward'  => $_POST['reward'],
				'uid'     => $_SESSION['uid'],
				'cid'     => $_POST['cid']
			);
			M('hd_ask')->add($data);
			$up = M('hd_user')->where("uid={$_SESSION['uid']}")->field('ask')->find();
			$up['ask']++;
			$dat=array(
				'ask'=>$up['ask'],
			);
			M('hd_user')->where("uid={$_SESSION['uid']}")->update($dat);
			$this->success('提问成功', __APP__);
			}
			$this->error('请登录后提问');
			
		}
		$money = M('hd_user')->where("uid={$_SESSION['uid']}")->field('point')->find();
		$this->assign('money', $money);
		$this->topCate();
		$this->display();
	}
	/**
	 * 获得子集分类
	 */
	public function ajaxGetSon(){
	   $cid = (int)$_POST['id'];
	   $data = M('hd_category')->where("pid={$cid}")->all();
	   //把php数组变成json返回给js
	   echo json_encode($data);
	}
	/**
	 * 回答方法
	 */
	 public function anw(){
	 	if(IS_POST){
	 		if(empty($_POST['content']))$this->error("回答内容不能为空");
			if(!isset($_SESSION['uid']))$this->error("请登录后回答");
	 		$data = array(
				'content' =>htmlspecialchars($_POST['content']),
				'time'	  =>time(),
				'uid'	  =>$_SESSION['uid'],
				'asid'	  =>$_POST['qid'],
			);
		M('hd_answer')->add($data);
		//用户回答数加1
		$up = M('hd_user')->where("uid={$_SESSION['uid']}")->field('answer')->find();
		$up['answer']++;
		$dat=array(
				'answer'=>$up['answer'],
			);
		M('hd_user')->where("uid={$_SESSION['uid']}")->update($dat);
		M('hd_ask')->exec("UPDATE hd_ask SET answer=answer+1 WHERE asid={$_POST['qid']}");
		$this->error("回答成功");
	 	}
	 }
	public function adopt(){
		$anid = $_GET['anid'];
		$anwarr = M('hd_answer')->where("anid={$anid}")->find();
		$askarr = M('hd_ask')->where("asid={$anwarr['asid']}")->find();
		if($askarr['solve']){
			$this->error("问题以有满意答案");
		};
//		p($anwarr);
//		问题表改成以解决
//		用户表采纳数加1
//		回答表改为被采纳
		M('hd_ask')->exec("UPDATE hd_ask SET solve=1 WHERE asid={$anwarr['asid']}");
		M('hd_ask')->exec("UPDATE hd_user SET accept=accept+1 WHERE uid={$_SESSION['uid']}");
		M('hd_ask')->exec("UPDATE hd_answer SET accept=1 WHERE anid={$anid}");
		$this->error("问题已经解决");
		
	}
}
